
<script setup>
import { ref, reactive } from 'vue'
import { onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'
import Breadcrumb from '../../components/Breadcrumb.vue'
import Dashboard from '../../components/Dashboard.vue'
import router from '../../router'
import { getUserById, updateUser, changePassword } from '@/api/user'

//判断折叠按钮是否显示
const isCollapse = ref(false)
//定义系统标题是否显示
const title = ref(true)

// 定义将后端返回的相对路径转换为完整URL 的工具方法
const toAbsoluteUrl = (u) => {
  if (!u) return u
  if (/^https?:\/\//i.test(u)) return u
  return `http://127.0.0.1:8080${u.startsWith('/') ? u : '/' + u}`
}

//定义用户信息
const user = ref({})

// 个人信息弹窗
const infoDialogVisible = ref(false)
const infoFormRef = ref()
const infoForm = reactive({ id: null, username: '', phone: '', dept: '', photo: '' })
const infoRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }]
}

// 修改密码弹窗
const pwdDialogVisible = ref(false)
const pwdFormRef = ref()
const pwdForm = reactive({ id: null, oldPassword: '', newPassword: '', confirmPassword: '' })
const pwdRules = {
  oldPassword: [{ required: true, message: '请输入旧密码', trigger: 'blur' }],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '至少6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== pwdForm.newPassword) callback(new Error('两次输入密码不一致'))
        else callback()
      },
      trigger: 'blur'
    }
  ]
}

onMounted(() => {
  const userStr = localStorage.getItem('user')
  if (userStr) {
    user.value = JSON.parse(userStr)
  }
})

//退出登录
const logout = () => {
  localStorage.removeItem('user')
  router.push('/')
}

//控制左侧菜单的展开与显示
const collapse = () => {
  isCollapse.value = !isCollapse.value
  if (isCollapse.value) {
    isCollapse.value = true
    title.value = false
  } else {
    title.value = false
  }
}

// 打开个人信息
const openInfo = async () => {
  if (!user.value?.id) {
    ElMessage.error('未获取到当前登录用户')
    return
  }
  try {
    const res = await getUserById(user.value.id)
    const data = res.data || res // 兼容后端Result结构或直接数据
    infoForm.id = data.id
    infoForm.username = data.username
    infoForm.phone = data.phone
    infoForm.dept = data.dept
    infoForm.photo = data.photo
    infoDialogVisible.value = true
  } catch (e) {
    ElMessage.error('获取个人信息失败')
  }
}

// 保存个人信息
const saveInfo = () => {
  infoFormRef.value?.validate(async (valid) => {
    if (!valid) return
    try {
      const payload = { ...infoForm }
      // 不携带密码字段，避免误改
      const res = await updateUser(payload)
      ElMessage.success('保存成功')
      // 同步本地用户缓存（显示名、头像等）
      const newUser = { ...user.value, ...payload }
      localStorage.setItem('user', JSON.stringify(newUser))
      user.value = newUser
      infoDialogVisible.value = false
    } catch (e) {
      ElMessage.error(e?.message || '保存失败')
    }
  })
}

// 打开修改密码
const openPwd = () => {
  if (!user.value?.id) {
    ElMessage.error('未获取到当前登录用户')
    return
  }
  pwdForm.id = user.value.id
  pwdForm.oldPassword = ''
  pwdForm.newPassword = ''
  pwdForm.confirmPassword = ''
  pwdDialogVisible.value = true
}

// 提交修改密码
const submitPwd = () => {
  pwdFormRef.value?.validate(async (valid) => {
    if (!valid) return
    try {
      await ElMessageBox.confirm('确认修改密码吗？', '提示', { type: 'warning' })
      const { id, oldPassword, newPassword } = pwdForm
      await changePassword({ id, oldPassword, newPassword })
      ElMessage.success('密码修改成功，请重新登录')
      // 退出登录
      logout()
    } catch (e) {
      if (e !== 'cancel') {
        ElMessage.error(e?.message || '修改失败')
      }
    }
  })
}

// 头像上传
const uploadAction = 'http://127.0.0.1:8080/api/upload'
const headers = { 'Authorization': localStorage.getItem('token') ? `Bearer ${localStorage.getItem('token')}` : '' }
const handleAvatarSuccess = (res) => {
  // 后端返回Result<String>，取res.data；保持相对路径存储到 infoForm.photo
  const val = (res && res.code === 200) ? res.data : (typeof res === 'string' ? res : '')
  if (val) {
    infoForm.photo = val
  }
}
</script>

<template>
  <div class="common-layout">
    <el-container>
      <el-aside :width="isCollapse? '64px' : '200px'">
        <div class="system-title">
          <img src="../../assets/sximages/logo.png" />
          <span>软件工程学院</span>
        </div>
        <el-menu default-active="home" class="el-menu-vertical-demo" @open="handleOpen" @close="handleClose" :collapse="isCollapse" unique-opened :collapse-transition="collapse-transition"  router>

          <el-menu-item index="home">
            <el-icon><i class="el-icon"><!-- placeholder --></i></el-icon>
            <template #title>
              <span>首页</span>
            </template>
          </el-menu-item>
          <el-sub-menu index="2">
            <template #title>
              <el-icon>
                <i class="el-icon"><!-- Tools icon placeholder --></i>
              </el-icon>
              <span>系统管理</span>
            </template>
            <el-menu-item index="/user">用户管理</el-menu-item>
            <el-menu-item index="/notice">通知管理</el-menu-item>
            <el-menu-item index="1-3">专业管理</el-menu-item>
            <el-menu-item index="1-4">班级管理</el-menu-item>
          </el-sub-menu>
          <el-sub-menu index="3">
            <template #title>
              <el-icon><i class="el-icon"><!-- School --></i></el-icon>
              <span>宿舍管理</span>
            </template>
            <el-menu-item index="/dormBuilding">楼宇管理</el-menu-item>
            <el-menu-item index="/dormRoom">房间管理</el-menu-item>
            <el-menu-item index="/checkin">入住管理</el-menu-item>
          </el-sub-menu>

          <el-sub-menu index="4">
            <template #title>
              <el-icon><i class="el-icon"><!-- Money --></i></el-icon>
              <span>财务管理</span>
            </template>
            <el-menu-item index="3-1">缴费管理</el-menu-item>
            <el-menu-item index="3-2">缴费记录</el-menu-item>
          </el-sub-menu>
          <el-sub-menu index="5">
            <template #title>
              <el-icon><i class="el-icon"><!-- Avatar --></i></el-icon>
              <span>学生管理</span>
            </template>
            <el-menu-item index="4-1">学生信息</el-menu-item>
            <el-menu-item index="4-2">报道信息</el-menu-item>
          </el-sub-menu>
          <el-sub-menu index="6">
            <template #title>
              <el-icon><i class="el-icon"><!-- Grid --></i></el-icon>
              <span>专业管理</span>
            </template>
            <el-menu-item index="/major">专业信息</el-menu-item>
          </el-sub-menu>
        </el-menu>
      </el-aside>
      <el-container>
        <el-header>
          <div class="collapse" @click="collapse">
            <el-icon :size="28" v-if="isCollapse" style="cursor: pointer;"><i class="el-icon"><!-- Expand --></i></el-icon>
            <el-icon :size="28" v-if="!isCollapse" style="cursor: pointer;"><i class="el-icon"><!-- Fold --></i></el-icon>
          </div>
          <span>新生报到服务平台</span>
          <!--右侧用户信息-->
          <div class="user-info">
            <img v-if="user?.photo" :src="toAbsoluteUrl(user.photo)" class="nav-avatar" />
            <img v-else src="../../assets/sximages//u169.svg" class="nav-avatar" />
            <el-dropdown>
              <span class="el-dropdown-link">
                {{ user.username }}
                <el-icon><ArrowDown /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu style="margin-top: 5px;">
                  <el-dropdown-item @click="openInfo">个人信息</el-dropdown-item>
                  <el-dropdown-item @click="openPwd">修改密码</el-dropdown-item>
                  <el-dropdown-item @click="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </el-header>
        <!-- 主体部分 --> 
        <el-main>
          <!-- 面包屑组件 -->
          <Breadcrumb></Breadcrumb>  
          <!-- 仪表盘组件 -->
          <Dashboard v-if="$route.path==='/home'"></Dashboard>
          <!-- 路由视图 -->
          <router-view></router-view>
        </el-main>
        <el-footer>Footer</el-footer>
      </el-container>
    </el-container>

    <!-- 个人信息弹窗 -->
    <el-dialog v-model="infoDialogVisible" title="个人信息" width="520px">
      <el-form ref="infoFormRef" :model="infoForm" :rules="infoRules" label-width="90px">
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            :action="uploadAction"
            :headers="headers"
            name="file"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
          >
            <img v-if="infoForm.photo" :src="toAbsoluteUrl(infoForm.photo)" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><i class="el-icon">+</i></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="infoForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="infoForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="部门">
          <el-input v-model="infoForm.dept" placeholder="请输入部门" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="infoDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveInfo">保 存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改密码弹窗 -->
    <el-dialog v-model="pwdDialogVisible" title="修改密码" width="520px">
      <el-form ref="pwdFormRef" :model="pwdForm" :rules="pwdRules" label-width="90px">
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input v-model="pwdForm.oldPassword" type="password" show-password placeholder="请输入旧密码" />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="pwdForm.newPassword" type="password" show-password placeholder="请输入新密码，至少6位" />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="pwdForm.confirmPassword" type="password" show-password placeholder="请再次输入新密码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="pwdDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitPwd">提 交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.common-layout {
  width: 100vw;
  height: 100%;
}

.el-aside {
  color: #333;
  line-height: 200px;
  overflow: hidden;
}

.el-header {
  background-color: rgb(242, 243, 245);
  color: #333;
  display: flex;
  line-height: 60px;
  padding: 0;
}

.el-main {
  background-color: #E9EEF3;
  color: #333;
  height: 625px;
}

.el-footer {
  background-color: #fefdf9;
  color: #333;
  text-align: center;
  line-height: 35px;
  height: 35px !important;
}

.system-title{
  width: 200px;
  height: 60px;
  background-color: rgb(143 ,1 ,0);
  line-height: 60px;
  position: relative;
  color: white;
  text-align: center;
  font-size: 20px;
  font-weight: bold;
  text-indent: 48px;
}
.system-title img{
  width: 50px;
  position: absolute;
  left: 10px;
  top: 5px;
}
.collapse{
  padding-top:10px;
  padding-left: 10px;
  line-height: 60px;
}
.el-header span{
  display: inline-block;
  line-height: 60px;
  font-size: 20px;
  margin-left: 10px;
}
.user-info{
  position: absolute;
  right: 150px;
  top: 10px;
}
.user-info{
  position: absolute;
  right: 10px;
  top: 5px;
  font-size: 2px;
}
:deep() .el-dropdown-link{
  outline: none;
  cursor: pointer;
  font-size: 24px;
}
.nav-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  object-fit: cover;
  margin-right: 8px;
}
.avatar-uploader .avatar {
  width: 80px;
  height: 80px;
  display: block;
  border-radius: 50%;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  line-height: 80px;
  text-align: center;
}
</style>